package com.herohead;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;



/**
 * @author david-1
 *
 */
public class Misc {

	public static long calculateDays(String startDate, String endDate)
	{
		@SuppressWarnings("deprecation")
		Date sDate = new Date(startDate);
		@SuppressWarnings("deprecation")
		Date eDate = new Date(endDate);
		Calendar cal3 = Calendar.getInstance();
		cal3.setTime(sDate);
		Calendar cal4 = Calendar.getInstance();
		cal4.setTime(eDate);
		return daysBetween(cal3, cal4);
	}

	/**
	 * @param message
	 * @return : the standard out of the command
	 * @throws Exception
	 * 
	 * run the command and return the standard out of the command
	 * 
	 */
	public static String callex(String message) throws Exception {

		try{
			Process p = Runtime.getRuntime().exec(message);




			BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));

			String line;
			String line2 = "";

			while ((line = input.readLine()) != null) {
				line2 = line2 + "\n" + line;
			}

			return line2;

		}catch( IOException ex ){
			return ex.toString();

		}
	}

	public static void callexNoWait(String message) throws Exception {

		try{
			Runtime.getRuntime().exec(message);
		}catch( IOException ex ){


		}
	}



	public static String checkNull(String s,boolean str) {
		if (s.length() == 0)
			if (str) s = null;
			else s = "0";
		return s;
	}


	/** Using Calendar - THE CORRECT WAY**/
	public static long daysBetween(Calendar startDate, Calendar endDate) {
		Calendar date = (Calendar) startDate.clone();
		long daysBetween = 0;
		while (date.before(endDate)) {
			date.add(Calendar.DAY_OF_MONTH, 1);
			daysBetween++;
		}
		return daysBetween;
	}

	public static String getIPaddressForHost(String hostname) {
		String s;
		try {
			InetAddress i = InetAddress.getByName(hostname);
			s= i.getHostAddress();
			//InetAddress.
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			s = e.getMessage();
		}
		return s;
	}

	public static String getLocalHostIPaddress() {
		String s;
		try {
			s = InetAddress.getLocalHost().toString();
			//InetAddress.
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			s = e.getMessage();
		}
		return s;
	}
	public static int getMonthNum(String monthstr) {

		monthstr = monthstr.toUpperCase();

		if (monthstr.equals("JAN")) return Calendar.JANUARY +1;
		if (monthstr.equals("FEB")) return Calendar.FEBRUARY +1;
		if (monthstr.equals("MAR")) return Calendar.MARCH +1;
		if (monthstr.equals("APR")) return Calendar.APRIL +1;
		if (monthstr.equals("MAY")) return Calendar.MAY +1;
		if (monthstr.equals("JUN")) return Calendar.JUNE +1;
		if (monthstr.equals("JUL")) return Calendar.JULY +1;
		if (monthstr.equals("AUG")) return Calendar.AUGUST +1;
		if (monthstr.equals("SEP")) return Calendar.SEPTEMBER + 1;
		if (monthstr.equals("OCT")) return Calendar.OCTOBER +1;
		if (monthstr.equals("NOV")) return Calendar.NOVEMBER +1;
		if (monthstr.equals("DEC")) return Calendar.DECEMBER +1;

		return 0;

	}
	public static String getMonthNumStr(String monthstr) {

		monthstr = monthstr.toUpperCase();

		if (monthstr.equals("JAN")) return "0" + Integer.toString((Calendar.JANUARY +1 ));
		if (monthstr.equals("FEB")) return "0" + Integer.toString((Calendar.FEBRUARY +1 ));
		if (monthstr.equals("MAR")) return "0" + Integer.toString((Calendar.MARCH +1 ));
		if (monthstr.equals("APR")) return "0" + Integer.toString((Calendar.APRIL +1 ));
		if (monthstr.equals("MAY")) return "0" + Integer.toString((Calendar.MAY +1 ));
		if (monthstr.equals("JUN")) return "0" + Integer.toString((Calendar.JUNE +1 ));
		if (monthstr.equals("JUL")) return "0" + Integer.toString((Calendar.JULY +1 ));
		if (monthstr.equals("AUG")) return "0" + Integer.toString((Calendar.AUGUST +1 ));
		if (monthstr.equals("SEP")) return "0" + Integer.toString((Calendar.SEPTEMBER +1 ));
		if (monthstr.equals("OCT")) return Integer.toString((Calendar.OCTOBER +1 ));
		if (monthstr.equals("NOV")) return Integer.toString((Calendar.NOVEMBER +1 ));
		if (monthstr.equals("DEC")) return Integer.toString((Calendar.DECEMBER +1 ));

		return null;

	}

	public static String getSystemInfoOSName() {
		return System.getProperty("os.name");
	}

	public static String getTimestamp() {
		String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime());
		return timeStamp;
	}

	public static String hashmd5(String s) throws NoSuchAlgorithmException{


		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(s.getBytes());

		byte byteData[] = md.digest();

		//convert the byte to hex format method 1
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < byteData.length; i++) {
			sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
		}

		//System.out.println("Digest(in hex format):: " + sb.toString());

		//convert the byte to hex format method 2
		/*  StringBuffer hexString = new StringBuffer();
    	for (int i=0;i<byteData.length;i++) {
    		String hex=Integer.toHexString(0xff & byteData[i]);
   	     	if(hex.length()==1) hexString.append('0');
   	     	hexString.append(hex);
    	}
    	//System.out.println("Digest(in hex format):: " + hexString.toString());
		 */
		return sb.toString();
	}

	@SuppressWarnings("unchecked")
	public static boolean isDate(String date) {

		ArrayList<SimpleDateFormat> dateFormats = new ArrayList<SimpleDateFormat>();
		//boolean validDate = false;
		dateFormats = loadFormats();
		@SuppressWarnings("unused")
		Date myDate = null;
		// add more date formats if you want

		for (SimpleDateFormat myFormat : dateFormats) {
			myFormat.setLenient(false);
			try {
				myDate = myFormat.parse(date);
				//System.out.println(myFormat.toPattern() + " : " + myDate.toGMTString());
				return true;
			} catch (Exception e) {
			}
		}
		return false;
	}

	@SuppressWarnings("rawtypes")
	private static ArrayList loadFormats() {



		ArrayList<SimpleDateFormat> dateFormats = new ArrayList<SimpleDateFormat>();
		dateFormats.add(new SimpleDateFormat("yyyy-MM-dd"));
		dateFormats.add(new SimpleDateFormat("yyyy MM dd"));
		dateFormats.add(new SimpleDateFormat("yyyy.MM.dd"));
		dateFormats.add(new SimpleDateFormat("yyyy-MMM-dd"));
		dateFormats.add(new SimpleDateFormat("yyyy MMM dd"));
		dateFormats.add(new SimpleDateFormat("yyyy.MMM.dd"));
		dateFormats.add(new SimpleDateFormat("dd-MM-yyyy"));
		dateFormats.add(new SimpleDateFormat("dd MM yyyy"));
		dateFormats.add(new SimpleDateFormat("dd.MM.yyyy"));
		dateFormats.add(new SimpleDateFormat("dd/MM/yyyy"));
		dateFormats.add(new SimpleDateFormat("dd-MM-yy"));
		dateFormats.add(new SimpleDateFormat("dd MM yy"));
		dateFormats.add(new SimpleDateFormat("dd.MM.yy"));
		dateFormats.add(new SimpleDateFormat("dd/MM/yy"));
		dateFormats.add(new SimpleDateFormat("dd-MMM-yy"));
		dateFormats.add(new SimpleDateFormat("dd MMM yy"));
		dateFormats.add(new SimpleDateFormat("dd.MMM.yy"));
		dateFormats.add(new SimpleDateFormat("dd/MMM/yy"));
		dateFormats.add(new SimpleDateFormat("dd-MMM-yyyy"));
		dateFormats.add(new SimpleDateFormat("dd MMM yyyy"));
		dateFormats.add(new SimpleDateFormat("dd.MMM.yyyy"));
		dateFormats.add(new SimpleDateFormat("dd/MMM/yyyy"));
		dateFormats.add(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"));
		dateFormats.add(new SimpleDateFormat("yyyy MM dd hh:mm:ss"));
		dateFormats.add(new SimpleDateFormat("yyyy.MM.dd hh:mm:ss"));
		dateFormats.add(new SimpleDateFormat("yyyy/MM/dd hh:mm:ss"));
		dateFormats.add(new SimpleDateFormat("yyyy-MMM-dd hh:mm:ss"));
		dateFormats.add(new SimpleDateFormat("yyyy MMM dd hh:mm:ss"));
		dateFormats.add(new SimpleDateFormat("yyyy.MMM.dd hh:mm:ss"));
		dateFormats.add(new SimpleDateFormat("yyyy/MMM/dd hh:mm:ss"));
		dateFormats.add(new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"));
		dateFormats.add(new SimpleDateFormat("dd MM yyyy hh:mm:ss"));
		dateFormats.add(new SimpleDateFormat("dd.MM.yyyy hh:mm:ss"));
		dateFormats.add(new SimpleDateFormat("dd/MM/yyyy hh:mm:ss"));
		dateFormats.add(new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss"));
		dateFormats.add(new SimpleDateFormat("dd MMM yyyy hh:mm:ss"));
		dateFormats.add(new SimpleDateFormat("dd.MMM.yyyy hh:mm:ss"));
		dateFormats.add(new SimpleDateFormat("dd/MMM/yyyy hh:mm:ss"));

		return dateFormats;
	}
	public static String readInFileToString(String filename) {

		BufferedReader br = null;
		String wholeFile= "";
		try {

			String sCurrentLine;


			br = new BufferedReader(new FileReader(filename));

			while ((sCurrentLine = br.readLine()) != null) {
				System.out.println(sCurrentLine);
				wholeFile = wholeFile + "\n" + sCurrentLine;
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null)br.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}


		return wholeFile;
	}


	public static List<String> reverseSort(String[] array) {
		List<String> aList = Arrays.asList(array);
		Collections.sort(aList, Collections.reverseOrder());
		return aList;
	}

	public String bytesToGB(String bytes) {

		if (Long.parseLong(bytes) > 1073741824) bytes = bytesToMB(bytesToKB(bytes));
		return bytes;

	}

	public String bytesToKB(String bytes) {


		try {
			if (Long.parseLong(bytes) > 1024) bytes = Long.toString((Long.parseLong(bytes) / 1024));
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			bytes = "-1";
		}
		return bytes;
	}


	public String bytesToMB(String bytes) {


		if (Long.parseLong(bytes) > 1048576) bytes = (bytesToKB(bytesToKB(bytes)));
		//	if (Long.parseLong(bytes) > 1048576) bytes = Long.toString((Long.parseLong(bytes) / 1048576));
		return bytes;

	}
	public boolean CheckForFile (String file2check) {
		File f = new File(file2check);
		if(f.exists()) {
			return true;
		} else {
			return false;
		}
	}

	public long convertToBytes(String sunit) {

		if (sunit == null){
			return 0;
		}

		long units = 0;
		int n = Integer.parseInt(sunit.split(" ")[0]);

		try {
			sunit = sunit.split(" ")[1];
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			return 0;
		}

		sunit = sunit.toUpperCase();

		if (sunit.equals("KB")) units = 1024;
		if (sunit.equals("MB")) units = 1048576;
		if (sunit.equals("GB")) units = 1073741824;
		//if (sunit.equals("TB")) units = 1099511627776;
		return n * units;
	}
	public long convertToMBytes(String sunit) {

		if (sunit == null){
			return 0;
		}

		//long units = 0;
		int n = Integer.parseInt(sunit.split(" ")[0]);

		try {
			sunit = sunit.split(" ")[1];
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			return 0;
		}

		sunit = sunit.toUpperCase();

		if (sunit.equals("KB")) n = 0;
		if (sunit.equals("MB")) n = n + 0;
		if (sunit.equals("GB")) n = n * 1024;
		if (sunit.equals("TB")) n = n * 1048576;


		return n;
	}
	public String getCurrentAMorPM() {
		SimpleDateFormat formatter = new SimpleDateFormat( "a" );
		return formatter.format( new java.util.Date() );
	}
	public String getCurrentDay() {
		SimpleDateFormat formatter = new SimpleDateFormat( "E" );
		return formatter.format( new java.util.Date() );
	}
	public String getCurrentDayInMonth() {
		SimpleDateFormat formatter = new SimpleDateFormat( "dd" );
		return formatter.format( new java.util.Date() );
	}
	public String getCurrentDayInYear() {
		SimpleDateFormat formatter = new SimpleDateFormat( "DD" );
		return formatter.format( new java.util.Date() );
	}

	public String getCurrentHour() {
		SimpleDateFormat formatter = new SimpleDateFormat( "HH" );
		return formatter.format( new java.util.Date() );
	}

	public String getCurrentMonth() {
		SimpleDateFormat formatter = new SimpleDateFormat( "MM" );
		return formatter.format( new java.util.Date() );
	}

	public String getCurrentWeekInYear() {
		SimpleDateFormat formatter = new SimpleDateFormat( "ww" );
		return formatter.format( new java.util.Date() );
	}


	public String getCurrentYear() {
		SimpleDateFormat formatter = new SimpleDateFormat( "yyyy" );
		return formatter.format( new java.util.Date() );
	}


	public String getCurrentYearMonth() {
		SimpleDateFormat formatter = new SimpleDateFormat( "yyyyMM" );
		return formatter.format( new java.util.Date() );
	}

	public int getMaxDaysInMonth() {
		Calendar c = Calendar.getInstance();
		return c.getActualMaximum(Calendar.DAY_OF_MONTH);
	}

	public String getMaxDaysInMonthStr() {
		Calendar c = Calendar.getInstance();
		int i = c.getActualMaximum(Calendar.DAY_OF_MONTH);
		return new Integer(i).toString();
	}

	public String getSystemInfoFileSeparator() {
		return System.getProperty("file.separator");
	}

	public String getSystemInfoJavaVersion() {
		return System.getProperty("java.version");
	}

	public String getSystemInfoUserName() {
		return System.getProperty("user.name");
	}

	public String getSystemLocalHostName() throws UnknownHostException {
		return  java.net.InetAddress.getLocalHost().getHostName();
	}


	public long getUnitValue(String sunit) {

		long units = 0;

		if (sunit.equals("KB")) units = 1024;
		if (sunit.equals("MB")) units = 1048576;
		if (sunit.equals("GB")) units = 1073741824;
		//if (sunit.equals("TB")) units = 1099511627776;
		return units;
	}

	public boolean plusminus(long source, long check, long source2) {

		if ((source - source2) > check)
			return true;
		if ((source - source2) < check)
			return true;


		return false;

	}

	public String readStdin() {

		String s = "";

		try{
			BufferedReader br =
					new BufferedReader(new InputStreamReader(System.in));

			String input;

			while((input=br.readLine())!=null){
				s = s + input + "\n";
				//System.out.println(input);
			}

			return s;
		}catch(IOException io){
			return "error reading standardin";
			//		io.printStackTrace();
		}
	}

	public String trimString(String str,int l) {
		if (str == null) {
			return str;
		}
		String tempStr = str;
		if (str.length() > l) tempStr= str.substring(0, l-1);

		return tempStr;

	}

}

